package org.exp3;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class CouDao {
    private static final String URL = "jdbc:mysql://localhost:3306/experiment3?useSSL=false&serverTimezone=UTC";
    private static final String USER = "mysql";
    private static final String PASS = "050601";

    private void logSQLException(SQLException e, String message) {
        System.err.println(message + ": " + e.getMessage());
        e.printStackTrace();
    }

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            System.err.println("MySQL JDBC 驱动未找到！");
            e.printStackTrace();
        }
    }

    /**
     * 获取所有课程信息
     *
     * @return 包含所有课程信息的列表
     */
    public List<Course> getAllCourese() {
        List<Course> list = new ArrayList<>();
        String sql = "SELECT * FROM course";

        // 执行数据库查询操作，获取所有课程记录
        try (Connection conn = DriverManager.getConnection(URL, USER, PASS);
             PreparedStatement ps = conn.prepareStatement(sql);
             ResultSet rs = ps.executeQuery()) {
            while (rs.next()) {
                Course cou = new Course(
                        rs.getInt("couid"),
                        rs.getString("couname"),
                        rs.getFloat("credits"),
                        rs.getString("hours"),
                        rs.getString("semester"),
                        rs.getInt("CouPno")
                );
                list.add(cou);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    public Course getCoureseById(int id) {
        String sql = "SELECT * FROM course WHERE couid = ?";
        Course cou = null;
        try (Connection conn = DriverManager.getConnection(URL, USER, PASS);
             PreparedStatement ps = conn.prepareStatement(sql);
        ) {
            ps.setInt(1, id);
            try (ResultSet rs = ps.executeQuery()) {
                if (rs.next()) {
                    cou = new Course(
                            rs.getInt("couid"),
                            rs.getString("couname"),
                            rs.getFloat("credits"),
                            rs.getString("hours"),
                            rs.getString("semester"),
                            rs.getInt("CouPno")
                    );
                }
            }
        } catch (SQLException e) {
            // 建议添加适当的日志记录或异常处理
            e.printStackTrace();
            // 或者抛出运行时异常
            // throw new RuntimeException("查询课程信息失败", e);
        }
        return cou;
    }

    /**
     * 添加课程信息
     *
     * @param cou 课程信息对象
     */
    public void addCourese(Course cou) {
        String sql = "INSERT INTO course (couid, couname, credits, hours, semester, CouPno) VALUES (?, ?, ?, ?, ?, ?)";
        try (Connection conn = DriverManager.getConnection(URL, USER, PASS);
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, cou.getCourseid());
            ps.setString(2, cou.getCoursename());
            ps.setFloat(3, cou.getCredits());
            ps.setString(4, cou.getHours());
            ps.setString(5, cou.getSemester());
            if (cou.getCouPno() == 0) {
                ps.setNull(6, java.sql.Types.INTEGER);
            } else {
                ps.setInt(6, cou.getCouPno());
            }

            ps.executeUpdate();
            System.out.println("添加成功！");
        } catch (SQLException e) {
            logSQLException(e, "添加课程信息失败");
        }
    }

    public boolean deleteCourese(int id) {
        String sql = "DELETE FROM course WHERE couid = ?";
        try (Connection conn = DriverManager.getConnection(URL, USER, PASS);
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, id);
            int rowsAffected = ps.executeUpdate();
            if (rowsAffected > 0) {
                System.out.println("控制台日志: 课程ID " + id + " 删除成功！");
                return true;
            } else {
                System.out.println("控制台日志: 删除课程失败，未找到课程ID " + id + " 的记录。");
                return false;
            }
        } catch (SQLException e) {
            logSQLException(e, "删除课程信息失败");
            return false;
        }
    }

    public boolean updateCourese(Course cou) {
        String sql = "UPDATE course SET couname = ?, credits = ?, hours = ?, semester = ?, CouPno = ? WHERE couid = ?";
        try (Connection conn = DriverManager.getConnection(URL, USER, PASS);
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, cou.getCoursename());
            ps.setFloat(2, cou.getCredits());
            ps.setString(3, cou.getHours());
            ps.setString(4, cou.getSemester());
            if (cou.getCouPno() == 0) {
                ps.setNull(5, java.sql.Types.INTEGER);
            } else {
                ps.setInt(5, cou.getCouPno());
            }
            ps.setInt(6, cou.getCouid());
            int rowsAffected = ps.executeUpdate();
            if (rowsAffected > 0) {
                System.out.println("控制台日志: 课程ID " + cou.getCouid() + " 修改成功！");
                return true;
            } else {
                System.out.println("控制台日志: 修改课程信息失败，未找到课程ID " + cou.getCouid() + " 的记录。");
                return false;
            }
        } catch (SQLException e) {
            logSQLException(e, "修改课程信息失败");
            return false;
        }
    }
}